package compiler.terminals;

import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import compiler.HowlToken;
import compiler.TokenReader;
import compiler.exceptions.HowlParserException;


public class Frequency extends HowlToken {
	

	private Long id;

	
	private TIMEUNIT timeunit;
	
	
	private OFTEN often;
	
	
	private String when;
	
	
	private Integer rate;

	public Frequency(TokenReader tokenReader) {
		super(tokenReader);
	}

	@Override
	public String codeGenerate() {
		String str = this.often.toString() + " ";
		if (often.equals(OFTEN.every)) {
			str += rate;
		} else {
			str += "at " + when;
		}
		return str;
	}

	@Override
	public HowlToken parse() throws HowlParserException {
		try {
			this.often = OFTEN.valueOf(this.tokenReader.consumeToken());
		} catch (IllegalArgumentException e) {
			throw new HowlParserException(this.tokenReader.getStatement(),
					this.tokenReader.getCharNo());
		}
		if (this.often.equals(OFTEN.daily)) {
			String la = this.tokenReader.nextToken();
			if (la.equals("at")) {
				this.tokenReader.consumeToken();
				this.when = this.tokenReader.consumeToken();
			} else {
				throw new HowlParserException(this.tokenReader.getStatement(),
						this.tokenReader.getCharNo());
			}
		} else if (this.often.equals(OFTEN.every)) {
			try {
				this.rate = Integer.parseInt(this.tokenReader.consumeToken());

				this.timeunit = TIMEUNIT.valueOf(this.tokenReader
						.consumeToken());
			} catch (NumberFormatException n) {
				throw new HowlParserException(this.tokenReader.getStatement(),
						this.tokenReader.getCharNo());
			}
		}
		return this;
	}

	/**
	 * @return the timeunit
	 */
	public TIMEUNIT getTimeunit() {
		return timeunit;
	}

	/**
	 * @param timeunit
	 *            the timeunit to set
	 */
	public void setTimeunit(TIMEUNIT timeunit) {
		this.timeunit = timeunit;
	}

	/**
	 * @return the often
	 */
	public OFTEN getOften() {
		return often;
	}

	/**
	 * @param often
	 *            the often to set
	 */
	public void setOften(OFTEN often) {
		this.often = often;
	}

	/**
	 * @return the when
	 */
	public String getWhen() {
		return when;
	}

	/**
	 * @param when
	 *            the when to set
	 */
	public void setWhen(String when) {
		this.when = when;
	}

	/**
	 * @return the rate
	 */
	public Integer getRate() {
		return rate;
	}

	/**
	 * @param rate
	 *            the rate to set
	 */
	public void setRate(Integer rate) {
		this.rate = rate;
	}
}
